#include "Select.h"

#include "RandomAccess.h"
#include "Utility.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void selectx
    (
        char* sourceRelation, 
        int Value,  
        int attr 
    )
{

    FILE* binFileIn = 
        fopen(getPrefixedFileNameByRelationNameWithExtension(sourceRelation,"I","bin"),"rb");
    assert(binFileIn != NULL);
    setbuf (binFileIn, NULL);
    fseek(binFileIn, 0, SEEK_END); 
    long endPosition = ftell(binFileIn)/(2 * sizeof(int));
    long startPosition = 0;


    long a = startPosition;
    long b = endPosition;
    long pos = (b-a)/2;

    int temp = getKeyInIndex(binFileIn, pos);
    while(temp != Value &&  (b-a)/2 != 0 )           
    {
        if( temp > Value)
            b = pos;
        else
            a = pos;
        pos = (b-a)/2 + a;
        temp = getKeyInIndex(binFileIn, pos);
    }

    if (temp == Value)
    {
        a = pos;
        b = pos;
        while (a > 0 && getKeyInIndex(binFileIn, a-1) == Value )
            a--;  

        while ( b < endPosition && getKeyInIndex(binFileIn, b+1) == Value)
            b++; 
    

        FILE* relationFile = fopen(getFileNameByRelationNameWithExtension(sourceRelation), "rb");
        if (relationFile == NULL)
        {
            printf("%s\n",getFileNameByRelationNameWithExtension(sourceRelation));
            assert(relationFile != NULL);
        }
        setbuf(relationFile, NULL);
        FILE* out = fopen(getFileNameByRelationNameWithExtension("out", "txt"), "a");
        if (out == NULL)
        {
            printf("%s\n", getPrefixedFileNameByRelationNameWithExtension(sourceRelation,"I","bin"));
            assert(out != NULL);
        }
        setbuf(out, NULL);

        for (long i = a; i <= b; i++)
        {
            int* t = getTupleInFileByNumber(relationFile, getValueInIndex(binFileIn, i));
            for (int j = 0; j < ARITY; j++)
            {
                fprintf(out, "%d ", t[j]);
            }
            fprintf(out, "\n");
        }

        fclose(out);
        fclose(relationFile);
        fclose(binFileIn);
    }
}

void select(
            char* sourceRelation, 
            int Value,  
            int attr 
            )
{
    FILE* fileBin = 
        fopen(getFileNameByRelationNameWithExtension(sourceRelation,"bin"),"rb");
    setbuf(fileBin, NULL);

    FILE* out = fopen(getFileNameByRelationNameWithExtension("out1", "txt"), "a");
    setbuf(out, NULL);

    int* tmp = new int[ARITY];
    int nBytes = 0;
    while((nBytes = fread(tmp,ARITY*sizeof(int),1,fileBin)) > 0)
    {
        if (tmp[attr] == Value)
        {
            for (int j = 0; j < ARITY; j++)
            {
                fprintf(out, "%d ", tmp[j]);
            }
            fprintf(out, "\n"); 
        }    
    }

    fclose(out);
    fclose(fileBin);
}
